<?php
class SP_Database_BaseCollector
{
	protected static $dbases = array();
	
	public static function addBase($name, $host, $encoding, $type, $root, $reader, $write)
	{
		$db = new SP_Database_BaseContainer;
		$db->name=$name;
		$db->host=$host;
		$db->encoding=$encoding;
		$db->type=$type;
		if(is_array($root))$db->setRoot($root['name'],$root['pass']);
		if(is_array($reader))$db->setReader($reader['name'],$reader['pass']);
		if(is_array($write))$db->setWriter($write['name'],$write['pass']);
		self::$dbases[strtolower($name)]=$db;
	}
	
	public static function getBase($name)
	{
		return self::$dbases[$name];
	}
	
	public static function get($name)
	{
		return self::getBase($name);
	}
	
	static public function getDoctrineConnection($name)
	{
		if( self::has($name) )
		{
			$db=self::get($name);
			$dsn = $db->type."://".$db->root['name'].":".$db->root['pass']."@".$db->host."/".$db->name;
			$doctrine_connection = Doctrine_Manager::connection($dsn, $db->name);
			$doctrine_connection->setCharset($db->encoding);
		}
		return $doctrine_connection;
	}
	
	public static function hasBase($name)
	{
		return isset(self::$dbases[$name]);
	}
	
	public static function has($name)
	{
		return self::hasBase($name);
	}
	
	public function remBase($name)
	{
		unset(self::$dbases[$name]);
	}
	
	public static function fromConfigurator($configurator,$path=NULL)
	{
		$bases=$configurator->getBaseJson($path);
		foreach($bases as $base)
		{
			self::addBase($base->name,$base->host,$base->encoding,$base->type,$base->root,$base->reader,$base->writer);
		}
	}
	
	public static function fromConfiguration(SP_Config_Configuration $config)
	{
		$bases=$config->getAll();
		foreach($bases as $base)
		{
			self::addBase($base->name,$base->host,$base->encoding,$base->type,$base->root,$base->reader,$base->writer);
		}
	}
	
	function __call($name,$vars) 
	{
		$mas=SP_Common_Functions::splitCamelCase($name);
		if ($mas[0]=='get' && count($mas)==3)
		{
			$name=$mas[1];
			$method='get'.ucfirst($mas[2]);
			if (isset(self::$dbases[$name]))
			{
				$out=self::$dbases[$name];
				return $out->$method();
			}
		}
		else
		{
			return  self::$dbases[$name];
		}
	}
	
}